package com.example.dell.fastshopping.user.UserInfo;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.network.http.BaseResponse;
import com.example.dell.fastshopping.user.entity.UserInfo;
import com.example.dell.fastshopping.utils.BaseUrlExternalStrageDir;
import com.example.dell.fastshopping.utils.GlideUtils;
import com.example.dell.fastshopping.utils.ImageSelectTool;
import com.example.dell.fastshopping.utils.RegexUtils;
import com.example.dell.fastshopping.utils.ToastUtils;
import com.example.dell.fastshopping.views.MaterialDialogUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ${YSH} on 2019/5/17.
 * 描述        ${TODO}
 * <p>
 * 更新者       $author$
 * 更新时间     $Data$
 * 描述         ${TODO}
 */
public class UserinfoActivity extends AppCompatActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.icon)
    ImageView userIcon;

    @BindView(R.id.name)
    TextView name;

    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.sex)
    TextView sex;

    @BindView(R.id.phone)
    TextView phone;

    private UserViewModle modle;
    private ImageSelectTool imageSelectTool;
    private MaterialDialog.Builder nikeNameBuilding;
    private UserInfo userInfo;
    private MaterialDialog.Builder sexBuilding;
    private MaterialDialog.Builder phoneBuilding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        initView();
    }

    public void initView() {
        title.setText("个人信息");
        modle = ViewModelProviders.of(this).get(UserViewModle.class);
        getdata();
        int width = 80;
        int height = 80;
        String path = BaseUrlExternalStrageDir.getBaseUrl() + "/user" + "temp.png";
        imageSelectTool = new ImageSelectTool(width, height, this, path, new ImageSelectTool.PicCallback() {
            @Override
            public void callback(final String url) {
                File file = new File(url);
                updateIcon(file);
            }

        });

        nikeNameBuilding = MaterialDialogUtils.showInputDialog(this, "编辑昵称", "昵称", new MaterialDialog.InputCallback() {
            @Override
            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                String s = input.toString().trim();
                if (s.isEmpty()) {
                    ToastUtils.showShort("请填写昵称");
                    return;
                }
                userInfo.setUserName(s);
                editUser(userInfo);
            }
        });
        sexBuilding = MaterialDialogUtils.showInputDialog(this, "编辑性别", "请填写男或女", new MaterialDialog.InputCallback() {
            @Override
            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                String s = input.toString().trim();
                if (s.isEmpty()) {
                    ToastUtils.showShort("请填写性别");
                    return;
                }
                if ("男".equals(s)) {
                    userInfo.setSex(1);
                } else if ("女".equals(s)) {
                    userInfo.setSex(0);
                } else {
                    ToastUtils.showShort("填写有误");
                    return;
                }
                editUser(userInfo);
            }
        });
        phoneBuilding = MaterialDialogUtils.showInputDialog(this, "编辑电话号码", "请填写电话号码", new MaterialDialog.InputCallback() {
            @Override
            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                String s = input.toString().trim();
                if (!RegexUtils.isMobileSimple(s)) {
                    ToastUtils.showShort("电话号码填写不正确");
                    return;
                }
                userInfo.setPhone(s);
                editUser(userInfo);
            }
        });

    }

    private void updateIcon(File file) {
        modle.updateIcon(file).observe(this, new Observer<BaseResponse>() {
            @Override
            public void onChanged(@Nullable BaseResponse userInfo) {
                getdata();
            }
        });
    }


    private void getdata() {
        modle.getUserBaseInfo().observe(this, new Observer<UserInfo>() {
            @Override
            public void onChanged(@Nullable UserInfo userInfo) {
                String icon = userInfo.getIcon();
                GlideUtils.setRoundView(UserinfoActivity.this, icon, userIcon);
                sex.setText(userInfo.getSex());
                name.setText(userInfo.getUserName());
                phone.setText(userInfo.getPhone());
                number.setText(userInfo.getId()+"");
                UserinfoActivity.this.userInfo = userInfo;
            }
        });
    }

    private void editUser(UserInfo userInfo) {

        modle.editUser(userInfo).observe(this, new Observer<BaseResponse>() {
            @Override
            public void onChanged(@Nullable BaseResponse response) {
                getdata();
            }
        });
    }

    @OnClick({R.id.back, R.id.edit_icon, R.id.editName, R.id.edit_sex, R.id.edit_phone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.edit_icon:
                _checkPermission();
                break;
            case R.id.editName:
                nikeNameBuilding.show();
                break;
            case R.id.edit_sex:
                sexBuilding.show();
                break;
            case R.id.edit_phone:
                phoneBuilding.show();
                break;
        }
    }


    private void _checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)//相机
                    != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)   //可读
                            != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)  //可写
                            != PackageManager.PERMISSION_GRANTED) {

                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                showIconDialog();
            }
        } else {
            showIconDialog();
        }
    }

    private void showIconDialog() {
        //成功时会返回相应的文件地址"/iden" + index + "temp.jpg"
        String path = BaseUrlExternalStrageDir.getBaseUrl() + "/user" + "temp.png";
        imageSelectTool.filePath = path;
        imageSelectTool.menuWindow.showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imageSelectTool.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (1 == requestCode) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)//相机
                    == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)   //可读
                            == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)  //可写
                            == PackageManager.PERMISSION_GRANTED) {
            } else {
                showIconDialog();
            }
        }
    }
}
